﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace Hzexe.Wechat.SharpSDK.Message.JSONData.User
{
    /// <summary>
    /// 用户详情
    /// </summary>
    [Serializable]
    public class UserInfoResult : Hzexe.Wechat.SharpSDK.Message.JSONData.Support.ResultBase
    {
        /// <summary>
        /// 用户是否订阅该公众号标识,值为0时，代表此用户没有关注该公众号，拉取不到其余信息。
        /// </summary>
        public bool subscribe { get; set; }
        /// <summary>
        /// 普通用户的标识，对当前公众号唯一
        /// </summary>
        public string openid { get; set; }
        /// <summary>
        /// 普通用户的昵称 
        /// </summary>
        public string nickname { get; set; }
        /// <summary>
        /// 普通用户的语言，简体中文为zh_CN 
        /// </summary>
        public string language { get; set; }
        /// <summary>
        /// 用户头像
        /// </summary>
        public string headimgurl { get; set; }
        /// <summary>
        /// 用户关注时间
        /// </summary>
        public long? subscribe_time { get; set; }
        /// <summary>
        /// 姓别
        /// </summary>
        public string sex { get; set; }
        /// <summary>
        /// 城市
        /// </summary>
        public string city { get; set; }
        /// <summary>
        /// 国家
        /// </summary>
        public string country { get; set; }
        /// <summary>
        /// 省份
        /// </summary>
        public string province { get; set; }


        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="OPENID">用户的openid</param>
        /// <returns></returns>
        public static new UserInfoResult GetResult(string OPENID)
        {
            var url = string.Format(
                @"https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}",
                Support.AccessTokenResult.AccessToken,
                OPENID
                );

            //AccessTokenResult
            string jsonstring = @"{""errcode"":40013,""errmsg"":""http request error""}";
            WebClient wc = new WebClient();
            wc.Encoding = System.Text.Encoding.UTF8;
            try
            {
                jsonstring = wc.DownloadString(url);
            }
            catch (Exception ex)
            {
                log.Warn("请求远程服务器" + url + "失败", ex);
            }
            finally
            {
                wc.Dispose();
            }

            return Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfoResult>(jsonstring);
        }
    }
}
